package com.yh.blog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义全局的异常处理
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    private final Logger logger=LoggerFactory.getLogger(this.getClass());

//    处理所有异常
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHander(HttpServletRequest request,Exception e) throws Exception {
        logger.error("Request Url {},Exception : {}",request.getRequestURL(),e);
//        如果标识了异常状态码那我们就抛给springboot进行处理，不用这个全局的异常处理器(自定义一些异常)
        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){
            throw e;
        }
        ModelAndView mv=new ModelAndView();
        mv.addObject("url",request.getRequestURL()).addObject("exception",e);
        mv.setViewName("error/error");
        return mv;
    }
}
